import requests
import os
import json
from urllib.parse import urljoin

# 基础URL和请求头
BASE_URL = "https://www.lingxisuxie.com"
HEADERS = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Referer': 'https://www.lingxisuxie.com/',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
    'sec-ch-ua': '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'token': 'UeYd6acGBQ3xo9vbWgbBevzoPqvjHPVcLQCMJ8vx9MBD7WBxfCk6n6ur9PJeiXfa'
}

def get_categories():
    """获取提示词分类数据"""
    url = urljoin(BASE_URL, "/api/prompt/category/with-count")
    response = requests.get(url, headers=HEADERS)
    if response.status_code == 200:
        return response.json().get("data", [])
    else:
        print(f"获取分类数据失败，状态码: {response.status_code}")
        return []

def get_template_list(category_id):
    """获取指定分类的模板列表"""
    url = urljoin(BASE_URL, f"/api/prompt/template/list")
    params = {
        "categoryId": category_id,
        "tag": 0,
        "current": 1,
        "size": 30,
        "orderBy": "use_count",
        "orderDirection": "desc"
    }
    response = requests.get(url, headers=HEADERS, params=params)
    if response.status_code == 200:
        return response.json().get("data", {}).get("records", [])
    else:
        print(f"获取分类 {category_id} 的模板列表失败，状态码: {response.status_code}")
        return []

def get_template_detail(template_id):
    """获取模板详情"""
    url = urljoin(BASE_URL, f"/api/prompt/template/{template_id}")
    response = requests.get(url, headers=HEADERS)
    if response.status_code == 200:
        return response.json().get("data", {})
    else:
        print(f"获取模板 {template_id} 的详情失败，状态码: {response.status_code}")
        return {}

def create_directory(dir_name):
    """创建目录"""
    # 确保目录名是有效的文件名
    safe_dir_name = "".join(c for c in dir_name if c.isalnum() or c in (' ', '_', '-')).rstrip()
    if not os.path.exists(safe_dir_name):
        os.makedirs(safe_dir_name)
        print(f"创建目录: {safe_dir_name}")
    return safe_dir_name

def create_json_file(dir_name, file_name, fields_data):
    """创建JSON文件"""
    # 确保文件名是有效的文件名
    safe_file_name = "".join(c for c in file_name if c.isalnum() or c in (' ', '_', '-', '.')).rstrip()
    # 确保文件名以.json结尾
    if not safe_file_name.endswith('.json'):
        safe_file_name += '.json'
    
    file_path = os.path.join(dir_name, safe_file_name)
    
    # 如果文件已存在，添加序号
    counter = 1
    original_file_path = file_path
    while os.path.exists(file_path):
        name, ext = os.path.splitext(original_file_path)
        file_path = f"{name}_{counter}{ext}"
        counter += 1
    
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(fields_data, f, ensure_ascii=False, indent=2)
    
    print(f"创建文件: {file_path}")

def main():
    # 第一步：获取所有分类
    categories = get_categories()
    print(f"获取到 {len(categories)} 个分类")
    
    # 第二步：遍历分类，创建文件夹，并处理模板
    for category in categories:
        category_id = category.get("id")
        type_name = category.get("typeName")
        
        print(f"处理分类: {type_name} (ID: {category_id})")
        
        # 创建以typeName命名的文件夹
        dir_name = create_directory(type_name)
        
        # 获取该分类下的模板列表
        templates = get_template_list(category_id)
        print(f"分类 {type_name} 下有 {len(templates)} 个模板")
        
        # 遍历模板列表，获取详情并创建文件
        for template in templates:
            template_id = template.get("id")
            template_name = template.get("name")
            
            # 获取模板详情
            detail = get_template_detail(template_id)
            if detail:
                fields_data = detail.get("fields", [])
                
                # 创建以模板name命名的json文件，并写入fields内容
                create_json_file(dir_name, template_name, fields_data)
            else:
                print(f"无法获取模板 {template_id} 的详情")

if __name__ == "__main__":
    main()